package riddles.content;

import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RiddlesFavView extends Activity {
	private String id;

	private TextView question;
	private Button delete;
	private Button answer;
	private Button phone;
	private ProgressDialog progressDialog = null;
	private Map<String, Object> map;
	private RiddlesDbAdapter mDbHelper;
	private Cursor c;
	private Map<String, Object> item;
	private Handler handler = new Handler();
	private static final int ANSWERDIALOG = 2;
	private Button preButton;
	private Button nextButton;
	private String nextorpre = "";// 用作判断是下一篇还是上一篇的标,为了显示是最后一篇还是第一篇

	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	View.OnTouchListener gestureListener;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		long[] weight =getWeight();
		String choose = AdChoose.choose(weight);
		if (choose.equals("wiyun")) {
			setContentView(R.layout.riddles_fav_view_wiyun);
		} else if (choose.equals("wooboo")) {
			setContentView(R.layout.riddles_fav_view_wooboo);
		} else if (choose.equals("youmi")) {
			setContentView(R.layout.riddles_fav_view_youmi);
		} else {
			setContentView(R.layout.riddles_fav_view_admob);
		}
		id = (String) getIntent().getExtras().get(BaseColumns._ID);
		question = (TextView) findViewById(R.id.fav_riddles_content);
		delete = (Button) findViewById(R.id.fav_delete_riddles);
		delete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				deleteItem((String) map.get(RiddlesDbAdapter.RIDDLESID));
			}
		});
		delete.setOnTouchListener(delTouchListener);

		preButton = (Button) findViewById(R.id.joke_previous);
		preButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				doPre();
			}
		});
		preButton.setOnTouchListener(previousListener);

		nextButton = (Button) findViewById(R.id.joke_next);
		nextButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				doNext();
			}
		});
		nextButton.setOnTouchListener(nextListener);

		answer = (Button) findViewById(R.id.fav_answer_riddles);
		answer.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(ANSWERDIALOG);
			}
		});
		answer.setOnTouchListener(answerListener);

		phone = (Button) findViewById(R.id.fav_phone_riddles);
		phone.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				sendSms(question.getText().toString());
			}
		});
		phone.setOnTouchListener(phoneListener);

		gestureDetector = new GestureDetector(new MyGestureDetector());
		gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (gestureDetector.onTouchEvent(event)) {
					return true;
				}
				return false;
			}
		};

		doSearch();
	}

	private void doSearch() {
		progressDialog = ProgressDialog.show(RiddlesFavView.this, "请稍等...",
				"获取显示内容...", true);
		new Thread() {
			public void run() {
				try {
					map = getMap(new Long(id));
					updateView();
				} catch (Exception e) {
					e.printStackTrace();
				}
				progressDialog.dismiss();
			}
		}.start();
	}

	private void doPre() {
		progressDialog = ProgressDialog.show(RiddlesFavView.this, "请稍等...",
				"获取显示内容...", true);
		new Thread() {
			public void run() {
				try {
					Map<String, Object> cmap = getPreMap(new Long(id));
					if (cmap != null) {// 这样操作是为了避免当是第一篇时,收藏该菜谱会报差
						map = cmap;
						nextorpre = "";
					} else {
						nextorpre = "pre";
					}
					updateView();
				} catch (Exception e) {
					e.printStackTrace();
				}
				progressDialog.dismiss();
			}
		}.start();
	}

	private void doNext() {
		progressDialog = ProgressDialog.show(RiddlesFavView.this, "请稍等...",
				"获取显示内容...", true);
		new Thread() {
			public void run() {
				try {
					Map<String, Object> cmap = getNextMap(new Long(id));
					if (cmap != null) {// 这样操作是为了避免当是最后篇时,收藏该菜谱会报差
						map = cmap;
						nextorpre = "";
					} else {
						nextorpre = "next";
					}
					updateView();
				} catch (Exception e) {
					e.printStackTrace();
				}
				progressDialog.dismiss();
			}
		}.start();
	}

	private Map<String, Object> getNextMap(Long rowId) {
		try {
			mDbHelper = new RiddlesDbAdapter(this);
			mDbHelper.open();
			c = mDbHelper.getNextContent(rowId);
			for (c.moveToFirst(); !c.isAfterLast();) {
				item = new HashMap<String, Object>();
				int cid = c.getColumnIndex(BaseColumns._ID);
				id = "" + c.getLong(cid);
				int riddlesid = c.getColumnIndex(RiddlesDbAdapter.RIDDLESID);
				int question = c.getColumnIndex(RiddlesDbAdapter.QUESTION);
				int answer = c.getColumnIndex(RiddlesDbAdapter.ANSWER);
				item.put(BaseColumns._ID, "" + c.getLong(cid));
				item.put(RiddlesDbAdapter.RIDDLESID, c.getString(riddlesid));
				item.put(RiddlesDbAdapter.QUESTION, c.getString(question));
				item.put(RiddlesDbAdapter.ANSWER, c.getString(answer));
				return item;
			}
		} catch (SQLException e) {
			setTitle("删除菜谱失败");
		} finally {
			mDbHelper.closeclose();
		}
		return null;

	}

	private Map<String, Object> getMap(Long rowId) {
		try {
			mDbHelper = new RiddlesDbAdapter(this);
			mDbHelper.open();
			c = mDbHelper.getContent(rowId);
			for (c.moveToFirst(); !c.isAfterLast();) {
				item = new HashMap<String, Object>();
				int id = c.getColumnIndex(BaseColumns._ID);
				int riddlesid = c.getColumnIndex(RiddlesDbAdapter.RIDDLESID);
				int question = c.getColumnIndex(RiddlesDbAdapter.QUESTION);
				int answer = c.getColumnIndex(RiddlesDbAdapter.ANSWER);
				item.put(BaseColumns._ID, "" + c.getLong(id));
				item.put(RiddlesDbAdapter.RIDDLESID, c.getString(riddlesid));
				item.put(RiddlesDbAdapter.QUESTION, c.getString(question));
				item.put(RiddlesDbAdapter.ANSWER, c.getString(answer));
				return item;
			}
		} catch (SQLException e) {
			setTitle("查询问题失败");
		} finally {
			mDbHelper.closeclose();
		}
		return null;

	}

	private Map<String, Object> getPreMap(Long rowId) {
		try {
			mDbHelper = new RiddlesDbAdapter(this);
			mDbHelper.open();
			c = mDbHelper.getPreContent(rowId);
			for (c.moveToFirst(); !c.isAfterLast();) {
				item = new HashMap<String, Object>();
				int cid = c.getColumnIndex(BaseColumns._ID);
				id = "" + c.getLong(cid);
				int riddlesid = c.getColumnIndex(RiddlesDbAdapter.RIDDLESID);
				int question = c.getColumnIndex(RiddlesDbAdapter.QUESTION);
				int answer = c.getColumnIndex(RiddlesDbAdapter.ANSWER);
				item.put(BaseColumns._ID, "" + c.getLong(cid));
				item.put(RiddlesDbAdapter.RIDDLESID, c.getString(riddlesid));
				item.put(RiddlesDbAdapter.QUESTION, c.getString(question));
				item.put(RiddlesDbAdapter.ANSWER, c.getString(answer));
				return item;
			}
		} catch (SQLException e) {
			setTitle("删除菜谱失败");
		} finally {
			mDbHelper.closeclose();
		}
		return null;

	}

	private void updateView() {
		handler.post(new Runnable() {
			public void run() {
				question.setText((String) map.get(RiddlesDbAdapter.QUESTION));
				if (nextorpre.equals("pre")) {
					showToast(Toast.LENGTH_SHORT, "这是第一篇");
				} else if (nextorpre.equals("next")) {
					showToast(Toast.LENGTH_SHORT, "这是最后一篇");
				}
			}
		});
	}

	private Dialog answerDialog(Context context) {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View textEntryView = inflater.inflate(
				R.layout.alert_dialog_answer, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setIcon(R.drawable.default_icon);
		builder.setTitle((String) map.get(RiddlesDbAdapter.ANSWER));
		builder.setView(textEntryView);
		builder.setPositiveButton(R.string.alert_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						removeDialog(ANSWERDIALOG);
					}
				});
		return builder.create();
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ANSWERDIALOG:
			return answerDialog(RiddlesFavView.this);
		}

		return null;
	}

	private void deleteItem(String riddlesid) {
		try {
			mDbHelper = new RiddlesDbAdapter(this);
			mDbHelper.open();
			mDbHelper.deleteDiary(riddlesid);
			Intent i = new Intent(RiddlesFavView.this, RiddlesFavList.class);
			startActivity(i);
		} catch (SQLException e) {
			setTitle("删除菜谱失败");
		} finally {
			mDbHelper.closeclose();
		}
	}

	protected void showToast(int type, String content) {

		View view = inflateView(R.layout.toast);

		TextView tv = (TextView) view.findViewById(R.id.tips);
		tv.setText(content);

		Toast toast = new Toast(this);
		toast.setView(view);
		toast.setDuration(type);
		toast.show();
	}

	private View inflateView(int resource) {
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		return vi.inflate(resource, null);
	}

	OnTouchListener phoneListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				// 更改为按下时的背景图片
				phone.setBackgroundResource(R.drawable.shareover);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				// 改为抬起时的图片
				phone.setBackgroundResource(R.drawable.share);
			}
			return false;
		}

	};
	OnTouchListener answerListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				// 更改为按下时的背景图片
				answer.setBackgroundResource(R.drawable.daianover);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				// 改为抬起时的图片
				answer.setBackgroundResource(R.drawable.daian);
			}
			return false;
		}

	};
	OnTouchListener delTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				// 更改为按下时的背景图片
				delete.setBackgroundResource(R.drawable.delover);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				// 改为抬起时的图片
				delete.setBackgroundResource(R.drawable.del);
			}
			return false;
		}

	};

	OnTouchListener previousListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				// 更改为按下时的背景图片
				preButton.setBackgroundResource(R.drawable.previousover1);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				// 改为抬起时的图片
				preButton.setBackgroundResource(R.drawable.previous);
			}
			return false;
		}

	};
	OnTouchListener nextListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				// 更改为按下时的背景图片
				nextButton.setBackgroundResource(R.drawable.nextover1);
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				// 改为抬起时的图片
				nextButton.setBackgroundResource(R.drawable.next);
			}
			return false;
		}

	};

	private void sendSms(String content) {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
		intent.putExtra(Intent.EXTRA_TEXT, content);
		startActivity(Intent.createChooser(intent, getTitle()));
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK，同时没有重复
			Intent i = new Intent(RiddlesFavView.this, RiddlesFavList.class);
			startActivity(i);
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	class MyGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					doNext();
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					doPre();
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (gestureDetector.onTouchEvent(event))
			return true;
		else
			return false;
	}
	
	private long[] getWeight() {
		WeightDbAdapter mDbHelper = new WeightDbAdapter(this);
		long[] l = new long[4];
		try {
			Cursor c;
			mDbHelper.open();
			c = mDbHelper.getAllNotes();
			startManagingCursor(c);
			if (c.getCount() > 0) {
				c.moveToFirst();
				int admob = c.getColumnIndex(WeightDbAdapter.ADMOB);
				int youmi = c.getColumnIndex(WeightDbAdapter.YOUMI);
				int wooboo = c.getColumnIndex(WeightDbAdapter.WOOBOO);
				int wiyun = c.getColumnIndex(WeightDbAdapter.WIYUN);
				l[0] = new Long(c.getString(admob));
				l[1] = new Long(c.getString(youmi));
				l[2] = new Long(c.getString(wooboo));
				l[3] = new Long(c.getString(wiyun));
				c.close();
			} else {
				l[0] = 1;
				l[1] = 1;
				l[2] = 1;
				l[3] = 1;
			}
			return l;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			mDbHelper.closeclose();
		}
		return l;
	}
}
